<?php
/**
  * IBD - Projet Helvetia - 2009
  *
  * Alexandre DOS SANTOS COELHO
  * Mathieu RICHARD
  * Karim EL-ALAILI
  * Julien REBETEZ
  *
  */

/**
 * Controlleur pour l'upload de fichiers
 */
class UploadsController extends AppController
{
    var $name = 'Uploads';
    var $components = array('FileHandler');
    var $uses = array('Upload');

    /**
     * Upload d'un fichier.
     * Si des donnees sont dans POST, upload ces donnees, sinon affiche le formulaire d'upload
     * @see views/uploads/admin_add.ctp
     */
    function admin_add() {
      if (isset($this->data)) {
        //les types mime acceptes
        $allowedMime = array( 
            'image/jpeg',          // images
            'image/pjpeg', 
            'image/png', 
            'image/gif', 

            'application/pdf',     // pdf
            'application/x-pdf', 
            'application/acrobat', 
            'text/pdf',
            'text/x-pdf', 

            'text/plain',          // text
            );

        //on utilise le champ 'extra_field' pour stocker le titre du fichier
        $dbFields = array('extra_field'  => $this->data['Upload']['extra_field']);

        //repertoire ou on stock les uploads
        $uploadDir = realpath(TMP);
        $uploadDir = WWW_ROOT.'upload';

        //on configure le composant filehandler
        $this->FileHandler->setAllowedMime($allowedMime);
        $this->FileHandler->setDebugLevel(1);
        $this->FileHandler->setRequired(1);
        $this->FileHandler->setHandlerType('db');
        $this->FileHandler->setDbModel('Upload');
        $this->FileHandler->addDbFields($dbFields);

        if ($this->FileHandler->upload('userfile', $uploadDir)) {
          //On sauvegarde l'association upload <-> evenement
          //L'upload a ete inserer par FileHandler->upload, on se contente donc de recuperer
          //l'id de la derniere insertion d'upload
          $this->Upload->id = $this->Upload->getLastInsertID();
      
          if (!empty($this->data['Event']['events_id'])) {
            $this->data['Event']['Event'] = array();
            foreach ($this->data['Event']['events_id'] as $ev_id) {
              $this->data['Event']['Event'][] = $ev_id;
            }
          }

          if ($this->Upload->save($this->data)) {
            $this->flashRedirect("Succes de l'upload", "/uploads");
          } else {
            $this->flash("Erreur lors de la validation<br /> Veuillez corriger");
          }
        } else {
          $this->flashRedirect("Echec de l'upload : ".$this->FileHandler->errorMessage, "/admin/uploads/add");
        }
      }
      $this->_set_events_titles();
    }

    /**
      * Remplis une variable $events_titles de la vue avec un dictionnaire id => titre des evenements
      */
    function _set_events_titles () {
      $events = $this->Upload->Event->findAll();
      $event_titles = array();
      foreach ($events as $e) 
        $event_titles[$e['Event']['id']] = $e['Event']['title']; 
      $this->set('events_titles', $event_titles);
    }

    /**
     * Remplis egalement une variable $events_selected de la vue avec une liste des id des evenements selectionnes
     */
    function _set_events_selected () {
      $event_selected = array();
      foreach ($this->data['Event'] as $e)
        $event_selected[] = $e['id'];
      $this->set('events_selected', $event_selected);

    }

    /**
     * Edition des fichiers
     * @param $id l'id du fichier a editer
     * @see views/uploads/admin_edit.ctp
     */
    function admin_edit ($id = null) {
      $this->Upload->id = $id;

      if (!empty($this->data)) {
        //sinon on affiche le formulaire d'edition
        $this->Upload->id = $id;

        $this->data['Event']['Event'] = array();
        foreach ($this->data['Event']['events_id'] as $ev_id)
          $this->data['Event']['Event'][] = $ev_id;

        if ($this->Upload->Event->validatesEvent() &&
            $this->Upload->save($this->data) ) {
          $this->flashRedirect('Fichier edité', '/uploads');
        } else {
          $this->__deleteCurrentUploadFromFS();
          $this->flash("Erreur lors de la validation<br /> Veuillez corriger");
        }
      }

      //On sauvegarde les erreurs de validation et on restaure apres 
      //le read, sans quoi on les perds
      $errors = $this->Upload->validationErrors;
      $this->data = $this->Upload->read();
      $this->Upload->validationErrors = $errors;

      $this->_set_events_titles();
      $this->_set_events_selected();
    }
   
    /**
     * Affichage d'un fichier unique
     * @param $id l'id du fichier a afficher
     */
    function view ($id = null) {
      $this->Upload->id = $id;
      $this->set('upload', $this->Upload->Read());
    }

    /**
     * Index des fichiers, affiche tous les fichiers
     * @see views/uploads/index.ctp
     */
    function index() {
    	$this->set('uploads', $this->Upload->findAll('ORDER BY created DESC'));
    }

    /**
     * Supprime l'upload etant represente par $this->Upload
     * du system de fichiers
     */
    function __deleteCurrentUploadFromFS () {
      @unlink(WWW_ROOT.'upload'.DS.$this->data['Upload']['subdir'].DS.$this->data['Upload']['file_name']);
 			@rmdir(WWW_ROOT.'upload'.DS.$this->data['Upload']['subdir']);
    }
    
    /**
     * Suppression d'un fichier
     * @param $id l'id du fichier a supprimer
     * @see views/uploads/admin_delete.ctp
     */
    function admin_delete($id=null) {
      $this->Upload->id = $id;
      $this->data = $this->Upload->read();
 		
      $this->__deleteCurrentUploadFromFS();

      $this->Upload->del($id);
      $this->flashRedirect('Fichier supprimé', '/uploads');
    }
}
?>
